package com.alinesno.cloud.base.notice.strategy;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.lang.exception.RpcServiceRuntimeException;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.alinesno.cloud.base.notice.entity.EmailErrorEntity;
import com.alinesno.cloud.base.notice.entity.EmailHistoryEntity;
import com.alinesno.cloud.base.notice.entity.EmailSendEntity;
import com.alinesno.cloud.base.notice.service.IEmailErrorService;
import com.alinesno.cloud.base.notice.service.IEmailHistoryService;

/**
 * <p>  服务实现类 </p>
 *
 * @author WeiXiaoJin
 * @since 2018-12-02 16:08:00
 */
@Service("email163_SendService")
public class Email163SendServiceImpl implements EmailSendStrategy {

	//日志记录
	private static final Logger log = LoggerFactory.getLogger(Email163SendServiceImpl.class);

	@Autowired
    private JavaMailSender javaMailSender ;

	@Autowired
	private IEmailHistoryService historyService ; 
	
	@Autowired
	private IEmailErrorService errorService ; 
	
	@Autowired
    private TemplateEngine templateEngine ;

	@Value("${spring.mail.username}")
	private String emailSender ; 
	
	@Override
	public ResponseEntity<EmailSendEntity> sendTextEmail(EmailSendEntity email) {
		SimpleMailMessage message = new SimpleMailMessage();
		
        try {
            message.setFrom(StringUtils.isNotBlank(email.getEmailSender())?email.getEmailSender():emailSender);
            message.setTo(email.getEmailReceiver());
            message.setSubject(email.getEmailSubject()) ; 
            message.setText(email.getEmailContent());
            
            javaMailSender.send(message);
            log.info("纯文本的邮件已经发送给【{}】.", email.getEmailReceiver());
           
            saveHistory(email)  ; 
        } catch (Exception e) {
        	log.error("纯文本邮件发送时发生异常！", e);
            saveError(email , e)  ; 
        }	
    
        return ResponseEntity.ok().body(email) ; 
	}

	@Override
	public ResponseEntity<EmailSendEntity> sendHtmlEmail(EmailSendEntity email) throws Exception {
		MimeMessage message = javaMailSender.createMimeMessage();
		
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(StringUtils.isNotBlank(email.getEmailSender())?email.getEmailSender():emailSender);
            helper.setTo(email.getEmailReceiver());
            helper.setSubject(email.getEmailSubject());
            helper.setText(email.getEmailContent(), true);
            
            javaMailSender.send(message);
            log.info("html邮件已经发送{}.", email.getEmailReceiver());
            
            saveHistory(email)  ; 
            
        } catch (MessagingException e) {
            log.error("发送html邮件时发生异常！", e);
            saveError(email , e)  ; 
            throw RpcServiceRuntimeException.error("发送html邮件时发生异常！" + e) ; 
        }
        
        return ResponseEntity.ok().body(email) ; 
	}

	@Override
	public ResponseEntity<EmailSendEntity> sendTemplateEmail(Map<String, Object> maps , String templateName , EmailSendEntity email) {
		final Context ctx = new Context(new Locale(""));
		
        if (null != maps && maps.size() != 0) {
            for (Map.Entry<String, Object> entry : maps.entrySet()) {
                ctx.setVariable(entry.getKey(), entry.getValue());
            }
        }
        final String htmlContent = templateEngine.process(templateName, ctx);
        final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
        
        try {
            message.setFrom(StringUtils.isNotBlank(email.getEmailSender())?email.getEmailSender():emailSender);
            message.setTo(email.getEmailReceiver());
            message.setSubject(email.getEmailSubject());
            message.setText(htmlContent, true);
            javaMailSender.send(mimeMessage);
            
            log.info("模板邮件已经发送{}.", email.getEmailReceiver());
            
            saveHistory(email)  ; 
        } catch (MessagingException e) {
            log.error("发送模板邮件【{}】时发生异常！{}", templateName , e);
            saveError(email , e)  ;
            throw new RpcServiceRuntimeException("发送模板邮件【"+templateName+"】时发生异常！") ; 
        }

		return null;
	}

	private void saveError(EmailSendEntity email , Exception e) {
		EmailErrorEntity err = new EmailErrorEntity() ; 
		err.setErrorMessage(e.getMessage());
		BeanUtils.copyProperties(email, err); 
		errorService.save(err) ; // 保存错误信息
	}

	/**
	 * 保存邮件历史记录
	 * @param email
	 */
	private void saveHistory(EmailSendEntity email) {
		EmailHistoryEntity his = new EmailHistoryEntity() ;
		BeanUtils.copyProperties(email , his); ; 
		historyService.save(his) ; 
	}

	@Override
	public ResponseEntity<EmailSendEntity> sendBatchTextEmail(List<EmailSendEntity> emails , String subject , String htmlBody) {
		return null;
	}

	@Override
	public ResponseEntity<EmailSendEntity> sendBatchHtmlEmail(List<EmailSendEntity> emails , String subject , String htmlBody) {
		return null;
	}

}